#! /usr/bin/env bash
# encoding: utf-8.0


ld_postgres="/lyndon/iSoft/postgres/lib"
ld_ivorysql="/lyndon/iSoft/IvorySQL/lib"


function join_by_flag() {
  local IFS="$1"
  shift
  echo "$*"
}


function join_by_flag2() {
  local IFS="$1"
  local filter_ld_paths="$2"
  joined=""
  for dir in ${filter_ld_paths}
  do 
    joined=${joined}${IFS}${dir}
  done
  echo "${joined}"
}

function filter_split_to_arr()
{
  local params="$1"
  local ld_path="$2"
  IFS=:
  declare -a to_arr
  i=1
  for dir in $params
  do
    if [ ${dir} == ${ld_postgres} -o ${dir} == ${ld_ivorysql} ]; then
      continue
    fi
    to_arr[$i]=${dir}
    let i+=1
  done

  to_arr[$i]=${ld_path}

  echo ${to_arr[@]}
}


function ld_split_join() {
  local ld_path="$1"
  local filter_ld_paths=($(filter_split_to_arr "${LD_LIBRARY_PATH}" "${ld_path}"))
  echo $(join_by_flag ':' ${filter_ld_paths})
}

case $1 in
  postgres)
    echo "postgres"
    echo "ORIGIN:"${LD_LIBRARY_PATH}
    # export LD_LIBRARY_PATH=$(ld_split_join "${ld_postgres}")
    filter_ld_paths=($(filter_split_to_arr ${LD_LIBRARY_PATH} ${ld_postgres}))
    echo "filter_ld_paths:"${filter_ld_paths[@]}
    export LD_LIBRARY_PATH=$(join_by_flag ':' ${filter_ld_paths[@]})
    echo "LD_LIBRARY_PATH:${LD_LIBRARY_PATH}"
    export PGHOME="/lyndon/iSoft/postgres"
    export PGDATA="/lyndon/iSoft/postgres_data"
    ;;
  ivorysql)
    echo "IvorySQL"
    echo "ORIGIN:"${LD_LIBRARY_PATH}
    # export LD_LIBRARY_PATH=$(ld_split_join "${ld_ivorysql}")
    filter_ld_paths=($(filter_split_to_arr ${LD_LIBRARY_PATH} ${ld_ivorysql}))
    echo "filter_ld_paths:"${filter_ld_paths[@]}
    export LD_LIBRARY_PATH=$(join_by_flag ':' ${filter_ld_paths[@]})
    echo "LD_LIBRARY_PATH:${LD_LIBRARY_PATH}"
    export PGHOME="/lyndon/iSoft/IvorySQL"
    export PGDATA="/lyndon/iSoft/ivorysql_data"
    ;;
  *)
    echo "Unknown the db type, must be postgres/ivorysql"
esac

# echo "LD_LIBRARY_PATH:${LD_LIBRARY_PATH}"